//
//  KSandboxTool.swift
//  Weibo
//
//  Created by 千山我独行 on 16/3/5.
//  Copyright © 2016年 千山我独行. All rights reserved.
//

import UIKit

class KSandboxTool: NSObject {
    
    // MARK: - 单例方法
    /// 创建单例
    static let sharedTool = KSandboxTool()
    
    /// 私有构造方法
    private override init() {
        
    }
    
    
}

extension KSandboxTool {
    
    // MARK: - 获取沙盒路径
    func getFilePath(urlString: String?) -> String {
        
        // 1、获取沙盒路径
        var sandboxPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        guard let urlPath = urlString else {
            return sandboxPath
        }
        
        // 2、拼接文件路径
        sandboxPath = (sandboxPath as NSString).stringByAppendingPathComponent((urlPath as NSString).lastPathComponent)
//        print("sandbox-\(sandboxPath)")
        return sandboxPath
    }
    
    
    // MARK: - 保存到沙盒
    func saveData(data: NSData, urlString: String) {
        let sandboxPath = getFilePath(urlString)
        data.writeToFile(sandboxPath, atomically: true)
    }
    
    // MARK: - 读取文件
    func readData(urlString: String) -> NSData? {
        let urlPath: String = getFilePath(urlString)
        let data = NSData(contentsOfFile: urlPath)
        return data
    }
    
}
